<script setup>
import {ref, onMounted, computed} from 'vue';
import eventBus from "@/EventBus"; // 导入 EventBus
import QRCode from 'qrcode.vue'; // 导入 QRCode 组件
import {addOrder} from "@/api/shop/order/"; // 假设这是你的创建订单的 API

const payStatus = ref(''); // 存储支付状态
const showQRCode = ref(false); // 控制二维码的显示
const input = ref('');
const services = ref([]); // 存储添加的服务
const showPaymentModal = ref(false); // 控制支付弹窗的显示
const orderIds = ref([]); // 存储订单 ID
const qrCodeUrl = ref(''); // 定义二维码 URL
const loadingQRCode = ref(false); // 控制二维码加载状态

// 计算总金额
const totalAmount = computed(() => {
  return services.value.reduce((sum, service) => sum + service.servicePrice * service.quantity, 0);
});

// 打开支付弹窗的处理函数
const openPaymentModal = async () => {
  console.log("去支付按钮被点击"); // 添加日志
  console.log("当前总金额:", totalAmount.value); // 输出当前总金额

  // 准备订单数据

  const orderData = reactive({

    queryParams: {
      pageNum: 1,
      pageSize: 10,
      userName: '刘师傅',
      paymoney:totalAmount.value, // 使用计算的总金额
      paymentType:null,
      orderStart: null,
      orderOver: null,
      orderPause: null,
      serviceName: services.value.map(service => service.serviceName).join(', '), // 连接服务名称
      orderStatus:'未开始',
      couponId: null,
      couponPrice: null,
      payStatus: '未支付',
      payTime: null,
      shopName:'天之道',
      employeeId: 3,
    },
  });
  const { queryParams } = toRefs(orderData);

  console.log("订单数据:", JSON.stringify(orderData, null, 2)); // 打印完整的订单数据

  try {
    // 发送请求到后端以创建订单
    const response = await addOrder(queryParams.value);
    console.log('API 响应:', response); // 打印响应
    if (response.code==200) {
      const data = await response;
      // 将新生成的订单 ID 存储在 orderIds 中
      console.log(data)
      orderIds.value.push(data.orderId);

      showPaymentModal.value = true; // 打开支付弹窗
      payStatus.value = '订单创建成功'; // 更新支付状态
    } else {
      const errorData = await response; // 尝试解析错误信息
      console.log(response)
      console.error('创建订单失败:', errorData.message || response.statusText);
      payStatus.value = '订单创建失败'; // 更新支付状态
    }
  }
  catch (error) {
    console.error('创建订单失败:', error.message || error);
    payStatus.value = '订单创建失败'; // 更新支付状态
  }
};

// 生成支付宝二维码
const generateAlipayQRCode = async () => {
  if (orderIds.value.length === 0) {
    console.error('没有可用的订单 ID');
    return;
  }

  loadingQRCode.value = true; // 开始加载二维码
  try {
    payStatus.value = '二维码生成中'; // 更新支付状态
    const orderId = orderIds.value[orderIds.value.length - 1];
    const response = await fetch(`/alipay/face2FacePay?orderId=${orderId}`, {
      method: 'GET',
    });

    if (response.ok) {
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      qrCodeUrl.value = url;
      showQRCode.value = true;
      payStatus.value = '二维码生成成功'; // 更新支付状态
    } else {
      console.error('生成二维码失败');
      payStatus.value = '二维码生成失败'; // 更新支付状态
    }
  } catch (error) {
    console.error('生成二维码失败', error);
    payStatus.value = '二维码生成失败'; // 更新支付状态
  } finally {
    loadingQRCode.value = false; // 结束加载二维码
  }
};

// 监听添加服务事件
onMounted(() => {
  eventBus.on('add-service', (service) => {
    services.value.push({...service, quantity: 1});
    input.value = service.serviceName; // 设置输入框的值
  });
});

// 删除服务的处理函数
const handleDelete = (index) => {
  services.value.splice(index, 1); // 删除指定索引的服务
};

// 更新数量的处理函数
const handleChange = (service, index) => {
  if (service.quantity <= 0) {
    handleDelete(index);
  }
};

// 搜索服务的处理函数
const handleUpdate = () => {
  console.log("搜索服务:", input.value);
};

// 关闭支付弹窗时重置状态
const closePaymentModal = () => {
  showPaymentModal.value = false;
  payStatus.value = ''; // 重置支付状态
  showQRCode.value = false; // 隐藏二维码
};
</script>

<template>
  <div class="left-pay">
    <div class="top">
      <el-input v-model="input" style="width: 240px;height: 45px;" placeholder="请输入服务名称"/>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" style="padding-top: 10px;">
          <el-button type="success" plain icon="Search" @click="handleUpdate" v-hasPermi="['shop:activity:edit']">搜索
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div class="under1-list">
      <ul>
        <li v-for="(service, index) in services" :key="service.id">
          <div class="list-left">
            <div class="list-left-img">
              <img :src="service.servicePic.startsWith('http') ? service.servicePic : require(`@/assets/images/${service.servicePic}`)" alt="" />
            </div>
            <div class="list-left-title" style="width: 100%">
              <div class="list-left-titlename">
                <h4>{{ service.serviceName }}</h4>
              </div>
              <div class="list-right">
                <div class="price-list">
                  <div>{{ service.servicePrice }}元</div>
                </div>
                <div class="time-list">
                  <div>{{ service.serviceTime }}min</div>
                </div>
                </div>
              <div class="input-number">
                <el-input-number
                    v-model="service.quantity"
                    :min="0"
                    :max="10"
                    @change="handleChange(service, index)"
                />
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="total">
      <div class="number-total" style="font-size: 20px; border-top: 1px solid; border-bottom: 1px solid;">
        <div>合计数量: {{ services.reduce((sum, service) => sum + service.quantity, 0) }}</div>
      </div>
      <div class="pay-total" style="font-size: 20px; border-bottom: 1px solid;">
        <div>合计金额: {{ totalAmount }}元</div>
      </div>
      <div class="payfor">
        <div class="mb">
          <el-button type="success" round @click="openPaymentModal">去支付</el-button>
        </div>
      </div>
    </div>
    <div v-if="showPaymentModal" class="payment-modal">
      <div class="modal-content">
        <h2>支付弹窗</h2>
        <p>总金额: {{ totalAmount }}元</p>
        <p v-if="payStatus" :style="{ color: payStatus.includes('成功') ? 'green' : 'red' }">{{ payStatus }}</p>
        <el-button @click="generateAlipayQRCode" :loading="loadingQRCode">生成支付宝二维码</el-button>

        <div v-if="showQRCode">
          <QRCode :value="qrCodeUrl" :size="200"/> <!-- 使用 QRCode 组件 -->
        </div>
        <button @click="closePaymentModal" class="close-button">关闭</button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 你的样式代码 */
.payfor {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  padding-top: 10px;
}

.under1-list {
  width: 100%;
  height: 450px; /* 设置最大高度 */
  overflow-y: auto; /* 超出部分显示滚动条 */
}

.input-number {
  display: flex;
  justify-content: flex-end;
  flex-grow: 1;
}

.left-pay {
  display: flex;
  justify-content: flex-start; /* 左对齐 */
  height: 100%;
  flex-direction: column; /* 垂直排列 */
}

.top {
  display: flex;
  justify-content: flex-start; /* 左对齐 */
  align-items: center; /* 垂直居中 */
}

.list-left-img {
  display: flex;
  align-items: center; /* 垂直居中 */

}

.list-left-img img {
  height: 70px;
  padding-left: 10px;
  width: 130px;
}

.list-left {
  display: flex;
  border-top-width: 1px;
  border-top-style: solid;
  border-bottom-width: 1px;
  border-bottom-style: solid;
}

ul {
  list-style-type: none; /* 去掉默认标记 */
  padding: 0; /* 去掉内边距 */
  margin: 0; /* 去掉外边距 */
}

.payment-modal {
  position: fixed; /* 固定定位 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center; /* 垂直和水平居中 */
  z-index: 1000; /* 确保在最上层 */
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); /* 阴影效果 */
  width: 400px; /* 固定宽度 */
  max-width: 90%; /* 最大宽度 */
}

.close-button {
  background-color: #f56c6c; /* 红色 */
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 5px; /* 圆角 */
  cursor: pointer;
  transition: background-color 0.3s; /* 平滑过渡效果 */
}

.close-button:hover {
  background-color: #f44336; /* 深红色 */
}
</style>
